import { ProColumns, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import {message, Modal, Select} from 'antd';
import React, {useEffect, useState} from 'react';
import {saveClassUsingPost, selectEmpIdAndNameUsingGet} from "@/services/tlias-backend/classController";

interface Props {
  visible: boolean;
  columns: ProColumns<API.Class>[];  // 定义列数据
  onSubmit: (values: API.ClassAddDTO) => void;
  onCancel: () => void;
}

/**
 * 创建弹窗
 * @param props
 * @constructor
 */
const CreateModal: React.FC<Props> = (props) => {
  const { visible, columns, onSubmit, onCancel } = props;
  const [teacherList, setTeacherList] = useState<{ id: number; name: string }[]>([]);

  // 获取班主任数据
  useEffect(() => {
    if (visible) {
      selectEmpIdAndNameUsingGet().then((response) => {
        if (response.code === 200) {
          setTeacherList(response.data as any);  // 设置班主任列表
        } else {
          message.error('获取班主任列表失败');
        }
      });
    }
  }, [visible]);

  /**
   * 添加节点
   * @param fields
   */
  const handleAdd = async (fields: API.ClassAddDTO) => {
    const hide = message.loading('正在添加');
    try {
      await saveClassUsingPost(fields);
      hide();
      message.success('创建成功');
      return true;
    } catch (error: any) {
      hide();
      message.error('创建失败，' + error.message);
      return false;
    }
  };

  // 修改columns，渲染班主任选择下拉框
  const updatedColumns = columns.map((column) => {
    if (column.dataIndex === 'empId') {  // 假设teacher是班主任字段的dataIndex
      return {
        ...column,
        renderFormItem: (item: any, { type, defaultRender, ...rest }:any, form:any) => {
          if (type === 'form') {
            return (
              <Select
                placeholder="请选择班主任"
                options={teacherList.map(teacher => ({
                  label: teacher.name,
                  value: teacher.id,
                }))}
                onChange={(value) => {
                  form.setFieldsValue({ empId: value });
                }}
              />
            );
          }
          return defaultRender(item);
        }
      };
    }
    return column;
  });

  return (
    <Modal
      destroyOnClose
      title="创建班级"
      open={visible}
      footer={null}
      onCancel={() => {
        onCancel?.();
      }}
    >
      <ProTable
        type="form"
        columns={updatedColumns}
        onSubmit={async (values: API.ClassAddDTO) => {
          console.log('提交的表单数据:', values);
          const success = await handleAdd(values);
          if (success) {
            onSubmit?.(values);
          }
        }}
      />
    </Modal>
  );
};
export default CreateModal;
